'''
Created on Jun 20, 2012

@author: thomas_dao
'''
import urls, util
import webapp2
from entity import Tag, Recipe
import recipe_async
from google.appengine.ext import ndb

class HomePageHandler(webapp2.RequestHandler):
    @ndb.synctasklet
    def get(self):
        recipes = []
        try:
            # Get all request input
            likes = self.request.GET.getall('like')
            hates = self.request.GET.getall('hate')
            others = self.request.GET.getall('hate') 
            
            # Get recipes from the input
            recipes = yield recipe_async.get_by_tags(likes, hates, others)
        except:
            pass
        
        # Get list of tags so front end can render
        tags = Tag.query().fetch()
        
        # Render HTML
        template = util.jinja_environment().get_template('home.html')
        self.response.out.write(template.render({"tags": tags, "recipes": recipes}))   
        
class LikeRecipeHandler(webapp2.RequestHandler):
    """
    Allow user to like a recipe. When user like a recipe, all tags within it
    got weight increase by 1
    """
    def post(self, recipe_id):
        entities = []
        
        # Get recipe from id
        recipe = Recipe.get_by_id(int(recipe_id))
        entities.append(recipe)
        
        # Increase recipe likes
        recipe.likes = recipe.likes + 1
        
        # Increase weight of all tags inside the recipe
        tags = ndb.get_multi(recipe.tags)
        for tag in tags:
            tag.weight = tag.weight + 1
            entities.append(tag)
            
        # Save the changes
        ndb.put_multi(entities)
        
        # Render to browser
        self.response.write(recipe.likes)
        
         
app = urls.app


def main():
    app.run()

if __name__ == '__main__':
    main()